#!/bin/bash

set -o errexit

test_dir=$(realpath $(dirname $0))
. ${test_dir}/../functions

set_debug

main() {
	create_infra $namespace

	cluster="demand-backup"
	spinup_pxc "$cluster" "$test_dir/conf/$cluster.yml"

	# We are using minio with tls enabled to check if `verifyTLS: false` works fine
	start_minio "demand-backup-ssl"

	run_backup "$cluster" "on-demand-backup-pvc"
	run_recovery_check "$cluster" "on-demand-backup-pvc"
	check_pvc_md5

	run_backup "$cluster" "on-demand-backup-pvc-bsource"
	run_recovery_check "$cluster" "on-demand-backup-pvc-bsource"

	run_backup "$cluster" "on-demand-backup-minio"
	run_recovery_check "$cluster" "on-demand-backup-minio"

	desc "Check backup deletion"
	kubectl_bin delete pxc-backup --all
	backup_exists=$(
		kubectl run -n "${NAMESPACE}" -i --rm aws-cli --image=perconalab/awscli --restart=Never -- \
			/usr/bin/env AWS_ACCESS_KEY_ID=some-access-key AWS_SECRET_ACCESS_KEY=some-secret-key AWS_DEFAULT_REGION=us-east-1 \
			/usr/bin/aws --endpoint-url https://minio-service:9000 --no-verify-ssl s3 ls operator-testing/ | grep -c "demand-backup" | cat
		exit "${PIPESTATUS[0]}"
	)
	if [[ $backup_exists -ne 0 ]]; then
		echo "Backup was not removed from bucket -- minio"
		exit 1
	fi

	destroy $namespace
	desc "test passed"

}

main
